<template>
  <a-modal
    :open="props.modelVisible"
    title="验收任务"
    ok-text="确认"
    cancel-text="取消"
    width="1000px"
    :body-style="{ height: '550px' }"
    @ok="onOk"
    @cancel="onCancel"
    :maskClosable="true"
    centered
  >
    <div style="height: 100%">
      <a-carousel arrows ref="carouselRef" :dots="false" :afterChange="onChange">
        <template #prevArrow>
          <div class="custom-slick-arrow" style="left: 10px; z-index: 1">
            <left-circle-outlined />
          </div>
        </template>
        <template #nextArrow>
          <div class="custom-slick-arrow" style="right: 10px">
            <right-circle-outlined />
          </div>
        </template>

        <div v-for="submission in props.submissionList">
          <div class="group-submission">
            <a-descriptions :column="3" bordered style="margin: 0">
              <a-descriptions-item label="所属小组" :span="1">{{
                submission.teamName
              }}</a-descriptions-item>
              <a-descriptions-item label="提交人" :span="1">{{
                submission.creatorName
              }}</a-descriptions-item>
              <a-descriptions-item label="完成时间" :span="1">{{
                dayjs(submission.createTime).format('YYYY-MM-DD  HH:mm:ss')
              }}</a-descriptions-item>
            </a-descriptions>

            <a-descriptions :column="2" bordered layout="vertical">
              <a-descriptions-item label="提交反馈" :span="1" style="width: 30%">
                <div style="height: 146px">
                  {{ submission.comment }}
                </div>
              </a-descriptions-item>
              <a-descriptions-item label="提交文件" :span="1">
                <div style="height: 146px; overflow-y: auto">
                  <a-list item-layout="horizontal" :data-source="submission.achievements">
                    <template #renderItem="{ item }">
                      <a-list-item>
                        <template #actions>
                          <DownloadOutlined class="attachment-down-icon" />
                        </template>
                        <a-list-item-meta
                          :description="`${formatBytes(item.size)} 来自 ${
                            item.creatorName
                          } | ${dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')}`"
                        >
                          <template #title>
                            <a>{{ item.achievementName }}</a>
                          </template>
                          <template #avatar>
                            <FileIcon :fileName="item.achievementName" size="30px" />
                          </template>
                        </a-list-item-meta>
                      </a-list-item>
                    </template>
                  </a-list>
                </div>
              </a-descriptions-item>
            </a-descriptions>
          </div>
        </div>
      </a-carousel>
      <a-divider style="margin: 5px 0"></a-divider>
      <div style="height: 40%; display: flex; justify-content: space-around">
        <div style="width: 45%">
          <a-card
            v-if="projectType == 2"
            :title="
              teacherEvaluation?.score
                ? '教师评分：' + teacherEvaluation?.score
                : '教师评分：未评分'
            "
            :bordered="false"
            style="height: 100%"
          >
            <p>{{ teacherEvaluation?.comment ? teacherEvaluation?.comment : '' }}</p>
          </a-card>
        </div>

        <a-divider type="vertical" style="height: 100%"></a-divider>
        <div style="height: 100%; width: 45%; display: flex; flex-direction: column">
          <a-form :model="formState" autocomplete="off" :disabled="!permission" ref="formRef">
            <div style="text-align: right; margin-bottom: 20px">
              <span>切换是否清空内容 : <a-checkbox v-model:checked="checked"> </a-checkbox></span>
            </div>
            <a-form-item label="评论" name="comment">
              <a-textarea v-model:value="formState.comment" :rows="4" />
            </a-form-item>

            <a-form-item label="分数" name="score">
              <a-input-number v-model:value="formState.score" :min="0" :max="100" :precision="2" />
            </a-form-item>
          </a-form>
        </div>
      </div>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
import { message } from 'ant-design-vue';
import TaskDao from '@/daos/task_dao';
import EvaluationDao from '@/daos/evaluation_dao';
import ProjectDao from '@/daos/project_dao';
import { useStore } from 'vuex';
import dayjs, { Dayjs } from 'dayjs';
const store = useStore();
const evaluationDap = new EvaluationDao();
const carouselRef = ref(null);
const index = ref();

const checked = ref(false);
// 切换到指定幻灯片
const goToSlide = (slideNumber, dontAnimate = true) => {
  if (carouselRef.value) {
    carouselRef.value.goTo(slideNumber, dontAnimate);
  }
};
//点击且或幻灯片逻辑
const onChange = (current) => {
  if (checked.value == true) {
    formRef.value.resetFields();
  } else {
    formRef.value.resetFields();
    getEvalutaion(current);
  }
  index.value = current;
};
//获取权限
const permission = store.getters.userPermission;
//modelVisible用于开关窗口，默认关闭
const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  submissionList: {
    type: Array<any>
  },
  index: {
    type: Number
  }
});
//emit用于修改窗口状态
const emit = defineEmits(['update:modelVisible', 'confirm']);

//项目类型
const projectType = store.getters.projectType;
//用户id
const userId = store.getters.userId;
//定义表单
const formRef = ref();
//教师留言内容
const teacherEvaluation = ref();
//企业人员留言内容
const managerEvaluation = ref();
//初始表单内容全为undefined
const formState = reactive({
  submissionId: null,
  evaluationId: null,
  score: null,
  comment: null
});
//获取教师和企业人员留言内容
const getEvalutaion = (current) => {
  teacherEvaluation.value = props.submissionList[current].evaluations.find(
    (evaluation) => evaluation.evaluationType == 1
  );
  managerEvaluation.value = props.submissionList[current].evaluations.find(
    (evaluation) => evaluation.evaluationType == 2
  );

  formState.submissionId = props.submissionList[current].submissionId;
  formState.evaluationId = managerEvaluation.value?.evaluationId;
  formState.score = managerEvaluation?.value?.score;
  formState.comment = managerEvaluation?.value?.comment;
};
const onOk = () => {
  const assignmentId = props.submissionList[index.value]?.assignmentId;
  formRef.value
    .validate()
    .then(() => {
      evaluationDap
        .insertOrUpdateEvaluations(
          [assignmentId],
          [formState.submissionId],
          formState.score,
          formState.comment,
          userId,
          dayjs(),
          2
        )
        .then((result) => {
          message.success(result.data.msg);
          emit('confirm');
        })
        .catch((error) => {
          console.error('新增或修改评论错误 insertOrUpdateEvaluations', error);
        });
    })
    .catch((error) => {
      console.log('数据验证失败:', error);
    });
};
const onCancel = () => {
  emit('update:modelVisible', false);
};
watch(
  () => props.modelVisible,
  (newValue) => {
    if (newValue === true) {
      index.value = props.index;
      getEvalutaion(index.value);
      goToSlide(index.value);
    }
  }
);

//文件大小转换
function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
</script>
<style scoped>
/* For demo */
:deep(.slick-slide) {
  height: 300px;
  overflow: hidden;
}

:deep(.slick-arrow.custom-slick-arrow) {
  width: 25px;
  height: 25px;
  font-size: 25px;
  color: #000000;
  background-color: rgba(0, 0, 0, 0.11);
  transition: ease all 0.3s;
  opacity: 0.3;
  z-index: 1;
}
:deep(.slick-arrow.custom-slick-arrow:before) {
  display: none;
}
:deep(.slick-arrow.custom-slick-arrow:hover) {
  color: #070202;
  opacity: 0.5;
}

.group-submission {
  width: 800px;
  height: 350px;
  margin: 0 auto;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.ant-descriptions {
  margin-bottom: 10px;
}

h3 {
  font-size: 14px;
  font-weight: bold;
  margin: 0 0 8px 0;
}

.scrollable-content {
  flex: 1;
  overflow-y: auto;
  padding-right: 8px; /* 避免滚动条遮挡内容 */
}

.scrollable-content p {
  margin: 0;
  white-space: pre-wrap; /* 保留换行符 */
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

ul li {
  margin-bottom: 5px;
}

a {
  color: #1890ff;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}
.attachment-down-icon :hover {
  color: #0958d9;
}
</style>
